<template>
  <page-container title="修改密码">
    <!-- 修改密码内容 -->
    <el-form
      :model="pwdForm"
      :rules="pwdRules"
      ref="pwdFormRef"
      label-width="80px"
    >
      <!-- 第一行 -->
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pwdForm.old_pwd" show-password></el-input>
      </el-form-item>

      <!-- 第二行 -->
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pwdForm.new_pwd" show-password></el-input>
      </el-form-item>

      <!-- 第三行 -->
      <el-form-item label="确认密码" prop="re_pwd">
        <el-input v-model="pwdForm.re_pwd" show-password></el-input>
      </el-form-item>

      <!-- 第四行 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('modify')"
          >修改密码</el-button
        >
        <el-button @click="submitForm('reset')">重置</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>

<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { userUpdatePasswordService } from '@/api/user'
import { ref } from 'vue'
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})
const validateOldPwd = (rule, value, callback) => {
  if (value === this.pwdForm.new_pwd) {
    callback(new Error('原密码不能和新密码相同'))
  } else {
    callback()
  }
}
const validateNewPwd = (rule, value, callback) => {
  if (value === this.pwdForm.old_pwd) {
    callback(new Error('新密码不能和原密码相同'))
  } else {
    callback()
  }
}
const validateRePwd = (rule, value, callback) => {
  if (value !== this.pwdForm.new_pwd) {
    callback(new Error('确认密码与新密码不一致'))
  } else {
    callback()
  }
}
const pwdRules = ref({
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
    { validator: validateOldPwd, trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
    { validator: validateNewPwd, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
    { validator: validateRePwd, trigger: 'blur' }
  ]
})

const submitForm = (type) => {
  this.$refs.pwdFormRef.validate((valid) => {
    if (valid) {
      if (type === 'modify') {
        // 执行修改密码逻辑
        console.log('密码修改成功', this.pwdForm)
      } else if (type === 'reset') {
        // 执行重置密码逻辑
        this.$refs.pwdFormRef.resetFields()
      }
    } else {
      this.$message.error('表单验证未通过，请检查输入')
      return false
    }
  })
}
</script>

<style lang="scss" scoped></style>
